<template>
    <div class="student-pending-schedule">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>待确认的课程安排</span>
                    <div>
                        <el-button type="primary" size="small" @click="refreshData" :loading="loading">刷新</el-button>
                        <el-button v-if="schedules.length > 0" type="info" size="small" @click="showDebugInfo">调试信息</el-button>
                        <el-button type="success" size="small" @click="goToMySchedule">我的课程安排</el-button>
                    </div>
                </div>
            </template>

            <el-alert
                type="info"
                show-icon
                :closable="false"
                title="提示"
                description="这里显示的是待确认的课程安排。如果是教师创建的课程，您可以选择确认或取消；如果是您自己创建的课程，您只能取消。"
                style="margin-bottom: 15px;"
            />

            <div v-if="loading" class="loading-container">
                <el-skeleton :rows="5" animated />
            </div>

            <div v-else-if="schedules.length === 0" class="empty-data-tip">
                <el-empty description="暂无待确认的课程安排" />
            </div>
            
            <el-table v-else :data="schedules" style="width: 100%">
                <el-table-column prop="tutoringTitle" label="课程名称" />
                <el-table-column prop="teacherName" label="教师姓名" />
                <el-table-column label="上课时间">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.startTime) }} - {{ formatDateTime(scope.row.endTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="location" label="上课地点" />
                <el-table-column prop="requirements" label="具体要求" show-overflow-tooltip />
                <el-table-column label="创建者">
                    <template #default="scope">
                        {{ scope.row.createdBy === 'TEACHER' ? '教师创建的' : '我创建的' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <!-- 如果是教师创建的课程，学生可以确认和取消 -->
                        <template v-if="scope.row.createdBy === 'TEACHER'">
                            <el-button 
                                type="success" 
                                size="small" 
                                @click="handleConfirm(scope.row)"
                            >
                                确认
                            </el-button>
                            <el-button 
                                type="danger" 
                                size="small" 
                                @click="handleCancel(scope.row)"
                            >
                                取消
                            </el-button>
                        </template>
                        <!-- 如果是学生自己创建的课程，学生只能取消 -->
                        <template v-else>
                            <el-button 
                                type="danger" 
                                size="small" 
                                @click="handleCancel(scope.row)"
                            >
                                取消
                            </el-button>
                        </template>
                        <el-button 
                            type="primary" 
                            size="small" 
                            @click="showPendingDetail(scope.row)"
                        >
                            详情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="课程详情" width="600px">
            <div v-if="currentSchedule" class="schedule-detail">
                <div class="detail-item">
                    <span class="label">课程名称：</span>
                    <span>{{ currentSchedule.tutoringTitle }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">教师姓名：</span>
                    <span>{{ currentSchedule.teacherName }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">上课时间：</span>
                    <span>{{ formatDateTime(currentSchedule.startTime) }} - {{ formatDateTime(currentSchedule.endTime) }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">上课地点：</span>
                    <span>{{ currentSchedule.location }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">具体要求：</span>
                    <span>{{ currentSchedule.requirements }}</span>
                </div>
            </div>
        </el-dialog>

        <!-- 调试信息对话框 -->
        <el-dialog v-model="debugDialogVisible" title="调试信息" width="800px">
            <pre class="debug-info">{{ JSON.stringify(originalData, null, 2) }}</pre>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { tutoringService } from '@/api/tutoring'
import { formatDateTime } from '@/utils/format'
import { useRouter } from 'vue-router'

const router = useRouter()
const schedules = ref([])
const detailDialogVisible = ref(false)
const currentSchedule = ref(null)
const loading = ref(false)
const debugDialogVisible = ref(false)
const originalData = ref(null)

// 获取学生的待确认课程安排
const getPendingSchedules = async () => {
    loading.value = true
    try {
        const response = await tutoringService.getStudentPendingSchedules()
        console.log('获取到的待确认课程安排数据:', response.data)
        
        // 打印每个课程的createdBy字段
        if (response.data && response.data.length > 0) {
            console.log('课程创建者信息:')
            response.data.forEach((item, index) => {
                console.log(`课程${index + 1} - ID: ${item.id}, 创建者: ${item.createdBy}, 教师ID: ${item.teacherId}, 学生ID: ${item.studentId}`)
            })
        }
        
        originalData.value = response.data
        schedules.value = response.data || []
        
        // 确保日期时间字段是Date对象
        if (schedules.value && schedules.value.length > 0) {
            schedules.value = schedules.value.map(schedule => {
                if (schedule.startTime && typeof schedule.startTime === 'string') {
                    schedule.startTime = new Date(schedule.startTime)
                }
                if (schedule.endTime && typeof schedule.endTime === 'string') {
                    schedule.endTime = new Date(schedule.endTime)
                }
                return schedule
            })
        }
    } catch (error) {
        console.error('获取待确认课程安排失败:', error)
        ElMessage.error('获取待确认课程安排失败: ' + (error.message || '未知错误'))
    } finally {
        loading.value = false
    }
}

// 刷新数据
const refreshData = () => {
    getPendingSchedules()
}

// 确认课程安排
const handleConfirm = async (schedule) => {
    // 学生只能确认教师创建的课程
    if (schedule.createdBy !== 'TEACHER') {
        ElMessage.error('您不能确认自己创建的课程安排，只有教师可以确认')
        return
    }
    
    try {
        await ElMessageBox.confirm('确认接受该课程安排？', '提示', {
            type: 'warning'
        })
        await tutoringService.updateStudentScheduleStatus(schedule.id, 1)
        ElMessage.success('已确认课程安排')
        getPendingSchedules()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('确认失败')
        }
    }
}

// 取消课程安排
const handleCancel = async (schedule) => {
    try {
        await ElMessageBox.confirm('确认取消该课程安排？', '提示', {
            type: 'warning'
        })
        await tutoringService.updateStudentScheduleStatus(schedule.id, 3)
        ElMessage.success('已取消课程安排')
        getPendingSchedules()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('取消失败')
        }
    }
}

// 显示详情
const showPendingDetail = (schedule) => {
    console.log('显示详情的课程安排:', schedule)
    // 确保日期时间字段是Date对象
    const detailSchedule = { ...schedule }
    if (detailSchedule.startTime && typeof detailSchedule.startTime === 'string') {
        detailSchedule.startTime = new Date(detailSchedule.startTime)
    }
    if (detailSchedule.endTime && typeof detailSchedule.endTime === 'string') {
        detailSchedule.endTime = new Date(detailSchedule.endTime)
    }
    currentSchedule.value = detailSchedule
    detailDialogVisible.value = true
}

// 显示调试信息
const showDebugInfo = () => {
    debugDialogVisible.value = true
}

// 跳转到我的课程安排页面
const goToMySchedule = () => {
    router.push('/student/schedule')
}

onMounted(() => {
    getPendingSchedules()
})
</script>

<style scoped>
.student-pending-schedule {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.schedule-detail {
    padding: 20px;
}

.detail-item {
    margin-bottom: 15px;
    line-height: 1.5;
}

.detail-item .label {
    font-weight: bold;
    margin-right: 10px;
    color: #666;
}

.empty-data-tip {
    padding: 20px;
    text-align: center;
}

.loading-container {
    padding: 20px;
}

.debug-info {
    white-space: pre-wrap;
    word-break: break-all;
    max-height: 500px;
    overflow-y: auto;
    background-color: #f5f5f5;
    padding: 10px;
    border-radius: 4px;
    font-family: monospace;
}
</style> 